import React, { Component } from 'react'
import css from './index.module.css'
import { Menu } from 'antd'
import { withRouter } from 'react-router-dom';
import routeList, { defaultRouteKey } from '../route';

class RouterMenu extends Component {
  state = {
    selectedRouteKey: {
      current: '',
      parent: ''
    }
  }
  onClick = (e) => {
    // console.log('click ', this.props.history, e);
    this.props.history.push(e.key)
    this.setState({ selectedRouteKey: {current: e.keyPath[0], parent: [...e.keyPath].slice(1)} })
  }
  mathRoute = (mapList, currentPath, parentRoute = null) => {
    let defaultRoute = {}
    for (const item of mapList) {
      if(item.key === defaultRouteKey) defaultRoute = item;
      if (currentPath === item.key) return { currentRoute: item, parentRoute };
      if (item.children) return this.mathRoute(item.children, currentPath, item)
    }
    return { currentRoute: defaultRoute, parentRoute }  //返回的parentRoute并没有使用，原因是给Menu组件设置openKeys后，不能展开收缩了
  }
  setSelectedRouter = () => {
    const { location: { pathname: currentPath } } = this.props;
    
    const route = this.mathRoute(routeList, currentPath);
    console.log('routeList', route);
    if(!route) return;
    const { currentRoute, parentRoute } = route;
    // console.log('RouterMenu setDefaultRouter', { currentRoute, parentRoute });
    this.setState({ selectedRouteKey: {current: currentRoute.key, parent: parentRoute.key} })
  }

  componentDidMount = () => {
    this.setSelectedRouter();
  }
  
  render() {
    // console.log('RouterMenu render');
    return (
      <div className={css.container}>
        <Menu
          onClick={this.onClick}
          style={{width: '100%'}}
          selectedKeys={this.state.selectedRouteKey.current}
          mode="inline"
          items={routeList}
        />
      </div>
    )
  }
}

//withRouter(组件)方法：将普通组件变为 路由组件，这样this.props中就有了history对象来操控路由
export default withRouter(RouterMenu)
